package com.dalei.vds.telephone.net;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NetConnection {
	
	public static boolean isValidIpAddress(String ipAddress) {
		String regex = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(ipAddress);
		return matcher.matches();
	}
	
	public static byte[] toBytesIpAddress(String ipAddress) {
		if (isValidIpAddress(ipAddress)) {
			String[] strArray = ipAddress.split("\\.");
			byte[] bytes = new byte[4];
			for (int i = 0; i < 4; i++) {
				bytes[i] = (byte) (Integer.parseInt(strArray[i]) & 0xff);
			}
			return bytes;
		} else {
			return null;
		}
	}
	
	public static String toStringIpAddress(byte[] addr) {
		if (addr.length == 4) {
			StringBuffer buffer = new StringBuffer();
			buffer.append(addr[0] >= 0 ? addr[0] : addr[0] + 256);
			buffer.append(".");
			buffer.append(addr[1] >= 0 ? addr[1] : addr[1] + 256);
			buffer.append(".");
			buffer.append(addr[2] >= 0 ? addr[2] : addr[2] + 256);
			buffer.append(".");
			buffer.append(addr[3] >= 0 ? addr[3] : addr[3] + 256);
			return buffer.toString();
		} else {
			return null;
		}
	}
	
	public static boolean isReachable(String ipAddress, int timeout) {
		byte[] addr = toBytesIpAddress(ipAddress);
		if (addr != null) {
			return isReachable(addr, timeout);
		} else {
			return false;
		}
	}
	
	public static boolean isReachable(byte[] addr, int timeout) {
		if (addr != null && addr.length == 4) {
			try {
				InetAddress ia = InetAddress.getByAddress(addr);
				return ia.isReachable(timeout);
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
		} else {
			return false;
		}
	}
	
	public static boolean isPortOpened(String host, int port) {
		Socket socket = null;
		try {
			socket = new Socket(host, port);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} finally {
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return true;
	}
}
